import MSLogger
import MSData
import socket
from datetime import datetime


def getCesarConnection(cesarConnectionParam):
    sock = None
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except (Exception), err:
        MSLogger.logError('CESAR: cannot create socket to %s:%s' % (str(cesarConnectionParam[0]), str(cesarConnectionParam[1])))
        return None

    try:
        sock.connect((cesarConnectionParam[0], cesarConnectionParam[1]))
    except (Exception), err:
        MSLogger.logError('CESAR: cannot connect to %s:%s' % (str(cesarConnectionParam[0]), str(cesarConnectionParam[1])))
        return None
    return sock

def checkCesarConnection(oldConn, connParams):
    return getCesarConnection(connParams)


def sendEvent(event, cesarConnection):
    packet  = chr(1)                #0
    try:
        packet += str(event.objectId) + chr(2)        #1
        packet += str(event.eventGenerateTime.strftime(MSData.TIME_FORMAT_CESAR)) + chr(2)  #2
        packet += 'message' + chr(2)    #3
        packet += str(event.contactIdZona) + chr(2)     #4
        packet += 'ZoneName' + chr(2)       #5
        packet += 'SectionNumber' + chr(2)    #6
        packet += str(event.contactIdFull) + chr(2)  #7
        packet += 'surgard' + chr(2)    #8
        packet += 'line' + chr(2)       #9
        packet += 'receiver' + chr(2)   #10
        packet += 'messageid' + chr(2)  #11
        packet += 'personId' + chr(2)   #12
        packet += 'messageGroup' + chr(2) #13
        packet += chr(3)          #14
        packet += 'comn' + chr(2)       #15
    except (Exception), err:
        MSLogger.logError('CESAR: cannot create packet with exception: %s' % (str(err)))

    try:
        cesarConnection.send(packet)
    except (Exception), err:
        MSLogger.logError('CESAR: cannot send packet %s with exception: %s' % (str(packet), str(err)))

def sendEvents(events, cesarConnection, cesarConnectionParam):
    if events == None or len(events) == 0:
        return cesarConnection

    try:
        cesarConnection = checkCesarConnection(cesarConnection, cesarConnectionParam)
        if cesarConnection != None:
            events.sort()
            for e in events:
                sendEvent(e, cesarConnection)
        
    except (Exception), err:
        MSLogger.logError('CESAR: cannot process events with exception: %s' % (str(err)))
    return cesarConnection


    
